package com.myl.admin.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.myl.admin.service.ISysMenuService;
import com.myl.core.domain.entity.SysMenu;
import com.myl.core.exception.ServiceExceptionHandler;
import com.myl.core.mapper.SysMenuMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

/**
 * <p>
 * 后台权限菜单节点  服务实现类
 * </p>
 *
 * @author Myl <ixiaomu@qq.com>
 * @since 2024-01-10 11:21
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    SysMenuMapper sysMenuMapper;

    /**
     *  <p>
     *   列表带分页数据
     *  </p>
     *
     * @return Page
     */
    @Override
    public List<?> getTreeList() {
        List<SysMenu>  list = getAllList();

        TreeNodeConfig config = new TreeNodeConfig();
        config.setParentIdKey("pid").setWeightKey("sort");

        // 转树
        List<Tree<String>> treeList = TreeUtil.build(list, "0", config, ((object, treeNode) -> {
            treeNode.setId(object.getId().toString());
            treeNode.setParentId(object.getPid().toString());
            treeNode.setName(object.getName());
            treeNode.setWeight(object.getSort());
            //扩展属性...
            treeNode.putExtra("perms", object.getPerms());
            treeNode.putExtra("status", object.getStatus());
        }));

        // 输出数据
        return treeList;
    }

    private List<SysMenu> getAllList() {
        QueryWrapper<SysMenu> wrapper = new QueryWrapper<SysMenu>();
        // 筛选及排序
        wrapper.eq("is_show",1).orderByAsc("sort", "id");
        // 输出数据
        return list(wrapper);
    }

    /**
     *  <p>
     *   详情数据
     *  </p>
     *
     * @return SysMenu
     */
    @Override
    public SysMenu getInfo(Long id) {

        SysMenu info = getById(id);
        // TODO 设置隐藏字段


        return info;
    }

    /**
     *  <p>
     *   新增或更新数据
     *  </p>
     * @param entity 节点实体
     * @return User
     */
    @Transactional
    @Override
    public SysMenu saveOrUpdateById(SysMenu entity) {
        boolean result;
        if (null == entity.getId()) {
            result = save(entity);
            // 新增子节点
            if (!entity.getChildren().isEmpty()){
                createChildrenNode(entity.getChildren(), entity);
            }
        } else {
            result = updateById(entity);
        }
        if (!result) {
            throw new ServiceExceptionHandler("数据入库失败！" );
        }
        return entity;
    }

    private void createChildrenNode(List<String> children, SysMenu entity){
        for (String child : children){
            SysMenu model = new SysMenu();
            model.setPid(entity.getId());
            model.setMenuType("A");
            model.setPerms(entity.getPerms()+':'+child);
            switch (child) {
                case "add":
                    model.setName("添加");
                    break;
                case "edit":
                    model.setName("编辑");
                    break;
                case "delete":
                    model.setName("删除");
                    break;
                case "changeStatus":
                    model.setName("更新状态");
                    break;
            }
            save(model);
        }
    }

    /**
    *  <p>
    *      批量删除
    *  </p>
    * @param ids ID集合
    * @return boolean
    */
    @Override
    public boolean deleteBatchByIds(List<Integer> ids) {
        return removeBatchByIds(ids);
    }

    @Override
    public Set<String> selectPermsByRoleId(Long roleId) {
        return null;
    }

    @Override
    public boolean checkFieldUnique(SysMenu entity, String field_name, String field_value) {
//        Long menuId = StringUtils.isNull(entity.getId()) ? -1L : entity.getId();
        QueryWrapper<SysMenu> wrapper = new QueryWrapper<SysMenu>();
        wrapper.eq(field_name, field_value);
        if (entity.getId() != null){
            wrapper.ne("id", entity.getId());
        }
        Long count = count(wrapper); // (entity.getName(), entity.getPid());
        return count > 0;
    }
}
